#!/usr/bin/bash

DEPENCIES_DIR=./depencies
INI_FILE=./backup.ini

isInstalled() {
	package=$1
	pip3 show $package >/dev/null 2>&1
	if [ $? -eq 0 ]; then
		return 0
	fi
	return 1
}

isExists() {
	path=$1
	ls $path >/dev/null 2>&1
	if [ $? -eq 0 ]; then
		return 0
	fi
	return 1
}

fd_install_depencies() {
	isInstalled "APScheduler"
	in1=$?
	isInstalled "crudini"
	in2=$?
	isInstalled "pymysql"
	in3=$?

	echo "in1 is $in1, in2 is $in2, in3 is $in3"
	if [[ $in1 -ne 0 ]] || [[ $in2 -ne 0 ]] || [[ $in3 -ne 0 ]]; then
		echo "will install $DEPENCIES_DIR/*"
		pip3 install $DEPENCIES_DIR/*
	fi

	isExists "/usr/bin/crudini"
	e1=$?
	isExists "/usr/local/bin/crudini"
	e2=$?
	if [[ $e1 -ne 0 ]] && [[ $e2 -eq 0 ]]; then
		ln /usr/local/bin/crudini -s /usr/bin/crudini
	fi
}

set_ini_value() {
	local section=$1
	local key=$2
	local value=$3

	echo "crudini --set $INI_FILE $section $key $value"
	crudini --set $INI_FILE $section $key $value
}

usage() {
	echo "please use as list:"
	echo "./backup.sh"
	echo "./backup.sh ftp"
	echo "./backup.sh restore"
	echo "./backup.sh restore ftp"
}

main() {
	if [ `id -u` -ne 0 ]; then
                echo "please use root privileges"
                exit
        fi

	fd_install_depencies


	#echo "\$# is $#"
	if [ $# -gt 2 ]; then
		usage
		exit 1
	fi

	if [ $# -eq 2 ]; then
		if [[ "x"$1 == "xrestore" ]]; then
			set_ini_value "conf" "backup_or_restore" "restore"
			if [[ "x"$2 == "xftp" ]] || [[ "x"$2 == "xlocal" ]]; then
				set_ini_value "restore" "restore_type" "$2"
			else
				usage
				exit 1
			
			fi
		elif [[ "x"$1 == "xbackup" ]]; then
			set_ini_value "conf" "backup_or_restore" "backup"
			if [[ "x"$2 == "xftp" ]] || [[ "x"$2 == "xlocal" ]]; then
				set_ini_value "backup" "backup_type" "$2"
			else
				usage
				exit 1
			fi
		else
			usage
			exit 1
		fi

	fi

	if [ $# -eq 1 ]; then
		if [[ "x"$1 == "xrestore" ]]; then
			set_ini_value "conf" "backup_or_restore" "restore"
			set_ini_value "restore" "restore_type" "local"
		elif [[ "x"$1 == "xbackup" ]]; then
			set_ini_value "conf" "backup_or_restore" "backup"
			set_ini_value "backup" "backup_type" "local"
		elif [[ "x"$1 == "xlocal" ]]; then
			set_ini_value "conf" "backup_or_restore" "backup"
			set_ini_value "backup" "backup_type" "local"
		elif [[ "x"$1 == "xftp" ]]; then
			set_ini_value "conf" "backup_or_restore" "backup"
			set_ini_value "backup" "backup_type" "ftp"
		else
			usage
			exit 1
		fi
	fi

	if [ $# -eq 0 ]; then
		set_ini_value "conf" "backup_or_restore" "backup"
		set_ini_value "backup" "backup_type" "local"
	fi

	python3 ./backup.py	

}

main $@
